package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderInfoService;

import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@SuppressWarnings("all")
public class OrderReceiver {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false") ,
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {
                    MqConst.ROUTING_WARE_ORDER
            }
    ))
    @SneakyThrows
    public void  stockMessageResult(String result,Message message,Channel channel){

        try {
            //判断
            if(!StringUtils.isEmpty(result)){

                //转换数据
                Map<String,String> map = JSON.parseObject(result, Map.class);
                //获取orderId
                long orderId = Long.parseLong(map.get("orderId"));
                //获取结果状态
                String status = map.get("status");

                //判断
                if("DEDUCTED".equals(status)){
                    //扣减库存成功
                    orderInfoService.updateOrderStatus(orderId,ProcessStatus.WAITING_DELEVER);

                }else{
                    orderInfoService.updateOrderStatus(orderId,ProcessStatus.STOCK_EXCEPTION);
                    //通知 补货


                }


            }
        } catch (Exception e) {
            //记录日志，通知人员进行处理，排查问题。。。。
            e.printStackTrace();
        }


        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }




    /**
     * 支付成功，修改订单状态
     * @param orderId
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    @SneakyThrows
    public void paySuccess(Long orderId,Message message,Channel channel){

        //判断
        if(orderId!=null){
            //查询订单信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            //判断
            if(orderInfo!=null && orderInfo.getOrderStatus().equals(OrderStatus.UNPAID.name())){

                //修改订单状态
                orderInfoService.updateOrderStatus(orderId, ProcessStatus.PAID);

                //发送消息到库存
                orderInfoService.sendOrderStatus(orderId);


            }


        }




        //确认消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    /**
     * 订单超时关闭监听
     * @param orderId
     * @param message
     * @param channel
     */
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    @SneakyThrows
    public void cancelOrder(Long orderId, Message message, Channel channel){

        try {
            //判断
            if(orderId!=null){

                //查询订单
                OrderInfo orderInfo = orderInfoService.getById(orderId);
                //判断是否支付
                if(orderInfo!=null &&"UNPAID".equals(orderInfo.getOrderStatus())&&"UNPAID".equals(orderInfo.getProcessStatus())){

                    //查询支付记录
                    PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    //判断
                    if(paymentInfo!=null &&paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.name())){
                        //有本地交易记录
                        //查询支付宝交易记录
                        boolean flag = paymentFeignClient.checkPayment(orderId);
                        //判断
                        if(flag){
                            //支付有记录--关闭支付宝记录
                            boolean result = paymentFeignClient.closePay(orderId);
                            //判断
                            if(result){
                                //关闭支付记录和订单状态
                                orderInfoService.execExpireOrder(orderId,"2");

                            }else{
                                //关闭支付宝记录失败----支付成功了。。。。
                                //不做任务处理

                            }


                        }else{

                            //关闭订单和本地交易记录
                            orderInfoService.execExpireOrder(orderId,"2");
                        }



                    }else{

                        //关闭订单--只关闭订单即可
                        orderInfoService.execExpireOrder(orderId,"1");
                    }


                }



            }
        } catch (Exception e) {
            //通知程序员。。。通知运维。。。通知运营。。。
            e.printStackTrace();
        }


        //确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);


    }
}
